﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace RobotPerCeption.utils
{
    public class ElementFinfdUtils
    {
        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                foreach (object rawChild in LogicalTreeHelper.GetChildren(depObj))
                {
                    if (rawChild is DependencyObject child)
                    {
                        if (child is T)
                        {
                            yield return (T)child;
                        }

                        foreach (T childOfChild in FindLogicalChildren<T>(child))
                        {
                            yield return childOfChild;
                        }
                    }
                }
            }
        }

        // 使用方法
        public List<RadioButton> findObjectByPropertyName(FrameworkElement elk, string propertyName)
        {
            List<RadioButton> radio = new List<RadioButton>();

            // 使用遍历方法
            foreach (RadioButton rb in LogicalTreeHelper.GetChildren(elk).OfType<RadioButton>())
            {
                if (rb.GroupName == propertyName)
                {
                    radio.Add(rb);
                }
            }

            return radio;


        }
    }
}
